package com.thinkit.security.custom;
import com.thinkit.core.base.BaseContextKit;
import com.thinkit.core.handler.CustomException;
import com.thinkit.security.config.AbsCustomJwtHandler;
import com.thinkit.utils.utils.Checker;
import com.thinkit.utils.utils.SpringContextHolder;
import lombok.Data;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * @Author LG
 * @Description 验证jwt是否有效
 * @Date 11:03 2019/4/30
 * @Param
 * @return
 **/
@Data
public class CustomJwtAuthenticationFilter extends OncePerRequestFilter {

	private RequestMatcher matcher;

	private JwtTokenStore tokenStore;

	private AbsCustomJwtHandler customJwtHandler;

	TokenExtractor tokenExtractor= SpringContextHolder.getBean(TokenExtractor.class);

	public CustomJwtAuthenticationFilter(RequestMatcher matcher, AbsCustomJwtHandler customJwtHandler) {
		this.matcher = matcher;
		this.customJwtHandler=customJwtHandler;
	}

	public CustomJwtAuthenticationFilter(RequestMatcher matcher, JwtTokenStore tokenStore, AbsCustomJwtHandler customJwtHandler) {
		this.matcher = matcher;
		this.tokenStore = tokenStore;
		this.customJwtHandler=customJwtHandler;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//提取token
		Authentication authentication = tokenExtractor.extract(request);
		if (Checker.BeNull(authentication)) {
			throw new AccessDeniedException("Invalid Jwt is invalid!");
		}
		try {
			customJwtHandler.handlerJwtToken(authentication,tokenStore,request);
		}catch (CustomException error){
			throw new AccessDeniedException(error.getMessage());
		}
		try {
			filterChain.doFilter(request, response);
		}finally {
			BaseContextKit.remove();
		}
	}
}
